//: typeinfo/pets/PetCreator.java
// Creates random sequences of Pets.
package java_thinking.unit_14.pets;
import java.util.*;

/**
 * 模板设计模式的一种变体
 * @author asd730520@live.com
 */

public abstract class PetCreator {
    private Random rand = new Random(47);
    // The List of the different types of Pet to create

    /**
     * 在list中创建不同类型的Pet
     * @return
     */
    public abstract List<Class<? extends Pet>> types();

    public Pet randomPet() { // Create one random Pet
        int n = rand.nextInt(types().size());
        try {
            /**
             * 返回类型被定义为“任何从pet导出的类”
             */
            return types().get(n).newInstance();
        } catch(InstantiationException e) {
            throw new RuntimeException(e);
        } catch(IllegalAccessException e) {
        throw new RuntimeException(e);
        }
    }
    public Pet[] createArray(int size) {
        Pet[] result = new Pet[size];
        for(int i = 0; i < size; i++)
            result[i] = randomPet();
        return result;
    }
    public ArrayList<Pet> arrayList(int size) {
        ArrayList<Pet> result = new ArrayList<Pet>();
        Collections.addAll(result, createArray(size));
        return result;
    }
} ///:~
